require 'rubygems'
require 'net/dns/mdns-sd'
require 'base64'

module Jakl
  class Client
    DNSSD = Net::DNS::MDNSSD
    
    @@debug = false
    
    def self.debug=(value)
      @@debug = value
    end
    
    def self.debug
      @@debug
    end
    
    def initialize(options={})
      default_options = {
        :default_recv => "jakl", 
        :timeout => 2, 
        :login => ENV['USER']
      }
      @options = default_options.merge(options)
    end
    
    def send(message, recv=nil)
      recv ||= @options[:default_recv]
      recv = recv.split(',').collect {|g| g.strip }
      puts "Sending: '#{message}' to '#{recv.join(',')}'" if @@debug
      
      find_recipients = DNSSD.resolve('jakl', '_jakl._tcp') do |r|
        puts "Found jakl service at #{r.target}" if @@debug
        recvs = r.text_record['recvs'].split(',').collect {|g| g.strip }
        puts "  responds to: #{recvs.join(', ')}"  if @@debug
        
        if (succ_recvs = recvs & recv).any?
          puts "Sending to: #{r.target}:#{r.port}" if @@debug
          
          # B64 Encoded NAME;GROUP;MESSAGE;
          data = [@options[:login], succ_recvs.join(','), message].map do |s| 
            Base64.encode64(s)
          end.join(';') + ";"
          TCPSocket.new(r.target, r.port).send(data, 0)
        end
      end
      
      sleep @options[:timeout]
      find_recipients.stop
    end
  end
end